//
//  MapHelper.m
//  CarCare
//
//  Created by ileo on 14/12/26.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "MapHelper.h"
#import "MapReGeocodeSimple.h"
#import "NetEngine.h"

#define K_MAP_KEY @"54b91f0923327eef82b4871f80738140"

@interface MapHelper()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locMgr;

@property (nonatomic, strong) MapReGeocodeSimple *reGeoCode;

@end

@implementation MapHelper

IMP_SINGLETON

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        [AMapServices sharedServices].apiKey = K_MAP_KEY;
        
        self.locMgr = [[CLLocationManager alloc] init];
        self.locMgr.delegate = self;
        
        // kCLLocationAccuracyNearestTenMeters:精度10米
        // kCLLocationAccuracyHundredMeters:精度100 米
        // kCLLocationAccuracyKilometer:精度1000 米
        // kCLLocationAccuracyThreeKilometers:精度3000米
        // kCLLocationAccuracyBest:设备使用电池供电时候最高的精度
        // kCLLocationAccuracyBestForNavigation:导航情况下最高精度，一般要有外接电源时才能使用
        [self.locMgr startMonitoringSignificantLocationChanges];
        self.locMgr.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        self.locMgr.distanceFilter = 10;
        self.locMgr.pausesLocationUpdatesAutomatically = NO;
        self.locMgr.activityType = CLActivityTypeFitness;
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
            [self.locMgr requestAlwaysAuthorization];
        }
    }
    return self;
}

-(MapReGeocodeSimple *)reGeoCode{
    if (!_reGeoCode) {
        _reGeoCode = [[MapReGeocodeSimple alloc] init];
    }
    return _reGeoCode;
}

+(NSString *)addressRoughlyFromReGeocode:(AMapReGeocode *)reGeocode{
    
    AMapReGeocode *regeocode = reGeocode;
    NSString *address = regeocode.formattedAddress;
    
    if (regeocode.pois.count > 0) {
        for (int i = 0; i < regeocode.pois.count; i++) {
            AMapPOI *poi = regeocode.pois[i];
            if ([poi.address isNotNil]) {
                NSString *path = [poi.name componentsSeparatedByString:@"("][0];
                address = [NSString stringWithFormat:@"%@(%@)附近",path,poi.address];
                break;
            }
        }
    }
    
    return address;
}

+(void)addressFromReGeocode:(AMapReGeocode *)reGeocode result:(void (^)(NSString *, NSString *, NSString *))result{
    if (result) {
        NSString *province = reGeocode.addressComponent.province;
        NSString *city = [reGeocode.addressComponent.city isNotNil] ? reGeocode.addressComponent.city : reGeocode.addressComponent.province;
        NSString *district = reGeocode.addressComponent.district;
        result(province,city,district);
    }
}

+(NSString *)addressPreciseFromReGeocode:(AMapReGeocode *)reGeocode{
    return reGeocode.formattedAddress;
}

+(NSString *)addressRoadFromReGeocode:(AMapReGeocode *)reGeocode{
    NSString *address = reGeocode.formattedAddress;
    NSArray *tmp = [address componentsSeparatedByString:@"市"];
    if (tmp.count > 1) {
        return [address substringFromIndex:((NSString *)tmp[0]).length + 1];
    }
    return address;
}

-(NSString *)amapKey{
    return K_MAP_KEY;
}

-(void)startUpdatingLoc{
    [self.locMgr startMonitoringSignificantLocationChanges];
    [self.locMgr startUpdatingLocation];
}

-(void)stopUpdatingLoc{
    [self.locMgr stopUpdatingLocation];
}

#pragma mark - 定位delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    self.userCoordinate = [[locations lastObject] coordinate];

//    [[[[NetEngine alloc] init] requestFullPath:@"http://10.8.6.112:8080/MTService/userProfile/test" withFullParams:@{@"lat":@(self.userCoordinate.latitude),@"lng":@(self.userCoordinate.longitude)} type:REQUEST_GET] requestOnly];
    
    __weak __typeof(self) wself = self;
    [self.reGeoCode reGeoCodeCoordinate:self.userCoordinate finish:^(NSString *poi, AMapReGeocode *reGeocode) {
        wself.currentReGeocode = reGeocode;
        [MapHelper addressFromReGeocode:reGeocode result:^(NSString *province, NSString *city, NSString *district) {
            wself.currentCity = city;
        }];
    } error:nil];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
}

-(BOOL)isLocAuthorization{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    return !(kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status);
}

+(void)checkLocAuthorization{
    if (![MAPMGR isLocAuthorization]) {
        TipsView *tipsV = [TipsView textTipsWithTitle:nil lightTitles:@[@"是否允许使用当前的地理位置",@"请于 设置－隐私－定位服务 进行设置"]];
        [tipsV addOKButton:@"我知道了" clickOK:^{
            [AlertMgr dismiss:TYPE_VIEW_ALERT];
        }];
        [AlertMgr showView:tipsV];
    }
}

#pragma make - navi

+(void)goNaviToCoordinate:(CLLocationCoordinate2D)coordinate{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"车挣",@"icz",coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }else{
        
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLoction = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
        [MKMapItem openMapsWithItems:@[currentLocation, toLoction] launchOptions:@{MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving}];
        
    }
}

@end
